package br.com.mensures.entitymanager;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import br.com.mensures.model.Pessoa;
import br.com.mensures.model.Usuario;

public class UsuarioManager {

	public boolean existe(Usuario usuario){
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();
		/*Query query = em.createQuery("select u from Usuario u where u.email = "
			 + ":pEmail and u.senha = :pSenha");
		query.setParameter("pEmail", usuario.getEmail());
		query.setParameter("pSenha", usuario.getSenha());
		*/
		Query query=em.createNativeQuery("SELECT PE.EMAIL,US.SENHA  FROM USUARIO US, PESSOA PE WHERE PE.EMAIL = ? AND US.SENHA = ?");
		query.setParameter(1, usuario.getPessoa().getEmail());
		query.setParameter(2, usuario.getSenha());
		
		boolean encontrado = !query.getResultList().isEmpty();
		
		em.getTransaction().commit();
		em.close();
		
		return encontrado;
	}
	public Pessoa buscaPorEmail(String email) {
		Pessoa pessoa = null;
		EntityManager em = JPAUtil.getEntityManager();
		em.getTransaction().begin();

		String jpql = "select c from Pessoa c where c.email =:email";
		TypedQuery<Pessoa> query = em.createQuery(jpql,Pessoa.class);
		query.setParameter("email", email.trim());
		pessoa = query.getResultList().get(0);
		em.getTransaction().commit();
		em.close();
		
		return pessoa;
	}

}
